/**
 * MCP服务器配置管理页面组件
 * 
 * 功能特性：
 * - MCP服务器配置列表展示和分页
 * - 服务器连接状态实时监控
 * - 创建、编辑、删除服务器配置
 * - 连接测试和状态管理
 * - 工具和资源同步
 * - 完整的表单验证
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Card,
  Modal,
  Form,
  Input,
  InputNumber,
  Switch,
  Select,
  message,
  Popconfirm,
  Alert,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  Descriptions,
  Tabs,
  List,
  Spin,
  Avatar
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ReloadOutlined, 
  ApiOutlined,
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  SyncOutlined,
  WifiOutlined,
  DisconnectOutlined,
  WarningOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import mcpServerService, {
  McpServerConfig,
  McpServerStatus,
  CreateMcpServerConfigDto,
  McpServerStats
} from '../../services/mcpServerService';

const { Option } = Select;
const { TextArea } = Input;

interface ServerConfig extends McpServerConfig {
  key?: string;
}

const McpServerList: React.FC = () => {
  const [configs, setConfigs] = useState<ServerConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [testLoading, setTestLoading] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [form] = Form.useForm<CreateMcpServerConfigDto>();
  const [editingConfig, setEditingConfig] = useState<ServerConfig | null>(null);
  const [stats, setStats] = useState<McpServerStats | null>(null);
  const [statuses, setStatuses] = useState<any[]>([]);
  const [selectedServer, setSelectedServer] = useState<ServerConfig | null>(null);
  const [serverTools, setServerTools] = useState<any[]>([]);
  const [serverResources, setServerResources] = useState<any[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    loadConfigs();
    loadStats();
    loadStatuses();
  }, [pagination.current, pagination.pageSize]);

  useEffect(() => {
    // 每30秒刷新一次状态
    const interval = setInterval(() => {
      loadStatuses();
      loadConfigs();
    }, 30000);

    return () => clearInterval(interval);
  }, []);

  const loadConfigs = async () => {
    try {
      setLoading(true);
      const response = await mcpServerService.getServerConfigs({
        skipCount: (pagination.current - 1) * pagination.pageSize,
        maxResultCount: pagination.pageSize,
      });
      
      setConfigs(response.items.map(item => ({ ...item, key: item.id })));
      setPagination(prev => ({
        ...prev,
        total: response.totalCount,
      }));
    } catch (error) {
      message.error('加载MCP服务器配置失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      const response = await mcpServerService.getServerStats();
      setStats(response);
    } catch (error) {
      console.error('加载统计失败:', error);
    }
  };

  const loadStatuses = async () => {
    try {
      const response = await mcpServerService.getAllServerStatuses();
      setStatuses(response);
    } catch (error) {
      console.error('加载状态失败:', error);
    }
  };

  const handleCreate = () => {
    setEditingConfig(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (config: ServerConfig) => {
    setEditingConfig(config);
    form.setFieldsValue({
      name: config.name,
      serverUrl: config.serverUrl,
      description: config.description,
      connectTimeoutMs: config.connectTimeoutMs,
      isActive: config.isActive
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await mcpServerService.deleteServerConfig(id);
      message.success('删除成功');
      loadConfigs();
      loadStats();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      setModalLoading(true);
      
      if (editingConfig) {
        await mcpServerService.updateServerConfig(editingConfig.id, values);
        message.success('更新成功');
      } else {
        await mcpServerService.createServerConfig(values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      loadConfigs();
      loadStats();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setModalLoading(false);
    }
  };

  const handleTestConnection = async (config: ServerConfig) => {
    try {
      setTestLoading(config.id);
      const result = await mcpServerService.testServerConnection(config.id);
      if (result.success) {
        message.success('连接测试成功');
      } else {
        message.error(`连接测试失败: ${result.message}`);
      }
      loadConfigs();
      loadStatuses();
    } catch (error) {
      message.error('连接测试失败');
    } finally {
      setTestLoading(null);
    }
  };

  const handleConnect = async (id: string) => {
    try {
      setActionLoading(id);
      await mcpServerService.connectServer(id);
      message.success('连接成功');
      loadConfigs();
      loadStatuses();
      loadStats();
    } catch (error) {
      message.error('连接失败');
    } finally {
      setActionLoading(null);
    }
  };

  const handleDisconnect = async (id: string) => {
    try {
      setActionLoading(id);
      await mcpServerService.disconnectServer(id);
      message.success('断开连接成功');
      loadConfigs();
      loadStatuses();
      loadStats();
    } catch (error) {
      message.error('断开连接失败');
    } finally {
      setActionLoading(null);
    }
  };

  const handleRestart = async (id: string) => {
    try {
      setActionLoading(id);
      await mcpServerService.restartServer(id);
      message.success('重启成功');
      loadConfigs();
      loadStatuses();
      loadStats();
    } catch (error) {
      message.error('重启失败');
    } finally {
      setActionLoading(null);
    }
  };

  const handleSyncTools = async (id: string) => {
    try {
      setActionLoading(id);
      const result = await mcpServerService.syncServerTools(id);
      message.success(`同步成功，共同步 ${result.toolCount || 0} 个工具`);
      loadConfigs();
      loadStats();
    } catch (error) {
      message.error('同步工具失败');
    } finally {
      setActionLoading(null);
    }
  };

  const handleViewDetail = async (config: ServerConfig) => {
    try {
      setSelectedServer(config);
      setDetailLoading(true);
      setDetailModalVisible(true);
      
      const [tools, resources] = await Promise.all([
        mcpServerService.getServerTools(config.id),
        mcpServerService.getServerResources(config.id)
      ]);
      
      setServerTools(tools.items || []);
      setServerResources(resources.items || []);
    } catch (error) {
      message.error('加载服务器详情失败');
    } finally {
      setDetailLoading(false);
    }
  };

  const getStatusColor = (status: McpServerStatus) => {
    const colors = {
      [McpServerStatus.Connected]: 'success',
      [McpServerStatus.Disconnected]: 'default',
      [McpServerStatus.Connecting]: 'processing',
      [McpServerStatus.Error]: 'error'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: McpServerStatus) => {
    const texts = {
      [McpServerStatus.Connected]: '已连接',
      [McpServerStatus.Disconnected]: '未连接',
      [McpServerStatus.Connecting]: '连接中',
      [McpServerStatus.Error]: '错误'
    };
    return texts[status] || '未知';
  };

  const getStatusIcon = (status: McpServerStatus) => {
    const icons = {
      [McpServerStatus.Connected]: <WifiOutlined />,
      [McpServerStatus.Disconnected]: <DisconnectOutlined />,
      [McpServerStatus.Connecting]: <SyncOutlined spin />,
      [McpServerStatus.Error]: <WarningOutlined />
    };
    return icons[status] || <DisconnectOutlined />;
  };

  const columns: ColumnsType<ServerConfig> = [
    {
      title: '服务器名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space direction="vertical" size="small">
          <strong>{text}</strong>
          <span style={{ fontSize: '12px', color: '#666' }}>
            {record.serverUrl}
          </span>
        </Space>
      ),
    },
    {
      title: '连接状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: McpServerStatus, record) => (
        <Space>
          {getStatusIcon(status)}
          <Badge
            status={getStatusColor(status) as any}
            text={getStatusText(status)}
          />
        </Space>
      ),
      filters: Object.values(McpServerStatus).map(status => ({
        text: getStatusText(status),
        value: status
      })),
      width: 120,
    },
    {
      title: '工具/资源',
      key: 'tools',
      render: (_, record) => (
        <Space size="small">
          <Tag color="blue">
            <ApiOutlined /> {record.toolCount || 0}
          </Tag>
          <Tag color="green">
            <SettingOutlined /> {record.resourceCount || 0}
          </Tag>
        </Space>
      ),
      width: 120,
    },
    {
      title: '超时设置',
      dataIndex: 'connectTimeoutMs',
      key: 'connectTimeoutMs',
      render: (timeout) => `${timeout}ms`,
      width: 100,
    },
    {
      title: '激活状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive) => (
        <Badge status={isActive ? 'success' : 'default'} text={isActive ? '激活' : '禁用'} />
      ),
      width: 100,
    },
    {
      title: '最后连接',
      dataIndex: 'lastConnectedAt',
      key: 'lastConnectedAt',
      render: (text) => text ? new Date(text).toLocaleString() : '-',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              size="small" 
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          
          <Tooltip title="测试连接">
            <Button 
              type="link" 
              size="small" 
              icon={<ApiOutlined />}
              loading={testLoading === record.id}
              onClick={() => handleTestConnection(record)}
            />
          </Tooltip>
          
          {record.status === McpServerStatus.Connected ? (
            <Tooltip title="断开连接">
              <Button 
                type="link" 
                size="small" 
                icon={<PauseCircleOutlined />}
                loading={actionLoading === record.id}
                onClick={() => handleDisconnect(record.id)}
              />
            </Tooltip>
          ) : (
            <Tooltip title="连接">
              <Button 
                type="link" 
                size="small" 
                icon={<PlayCircleOutlined />}
                loading={actionLoading === record.id}
                onClick={() => handleConnect(record.id)}
              />
            </Tooltip>
          )}
          
          <Tooltip title="重启">
            <Button 
              type="link" 
              size="small" 
              icon={<ReloadOutlined />}
              loading={actionLoading === record.id}
              onClick={() => handleRestart(record.id)}
            />
          </Tooltip>
          
          <Tooltip title="同步工具">
            <Button 
              type="link" 
              size="small" 
              icon={<SyncOutlined />}
              loading={actionLoading === record.id}
              onClick={() => handleSyncTools(record.id)}
            />
          </Tooltip>
          
          <Tooltip title="编辑">
            <Button 
              type="link" 
              size="small" 
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个服务器配置吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                size="small" 
                danger 
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="服务器总数"
              value={stats?.totalServers || 0}
              prefix={<ApiOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已连接"
              value={stats?.connectedServers || 0}
              prefix={<WifiOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总工具数"
              value={stats?.totalTools || 0}
              prefix={<SettingOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总资源数"
              value={stats?.totalResources || 0}
              prefix={<EyeOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="MCP服务器配置管理"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={() => { loadConfigs(); loadStatuses(); }}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              添加服务器
            </Button>
          </Space>
        }
      >
        <Alert
          message="MCP服务器配置管理"
          description="管理Model Context Protocol (MCP)服务器配置，配置完成后系统将自动连接到MCP服务器并同步可用的工具和资源。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Table
          columns={columns}
          dataSource={configs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || prev.pageSize,
              }));
            },
          }}
        />
      </Card>

      {/* 创建/编辑配置模态框 */}
      <Modal
        title={editingConfig ? '编辑MCP服务器配置' : '添加MCP服务器'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        confirmLoading={modalLoading}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
        >
          <Form.Item
            name="name"
            label="服务器名称"
            rules={[
              { required: true, message: '请输入服务器名称' },
              { min: 2, max: 50, message: '名称长度在2-50个字符之间' }
            ]}
          >
            <Input placeholder="请输入服务器名称" />
          </Form.Item>

          <Form.Item
            name="serverUrl"
            label="服务器URL"
            rules={[
              { required: true, message: '请输入服务器URL' },
              { type: 'url', message: '请输入有效的URL' }
            ]}
          >
            <Input placeholder="例如：ws://localhost:8080 或 https://api.example.com/mcp" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea 
              rows={3} 
              placeholder="请输入服务器描述"
              maxLength={500}
              showCount
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="connectTimeoutMs"
                label="连接超时时间（毫秒）"
                rules={[
                  { required: true, message: '请输入连接超时时间' },
                  { type: 'number', min: 1000, max: 300000, message: '超时时间在1000-300000毫秒之间' }
                ]}
                initialValue={30000}
              >
                <InputNumber 
                  min={1000} 
                  max={300000}
                  style={{ width: '100%' }}
                  placeholder="30000"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="isActive"
                label="激活状态"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch checkedChildren="激活" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 服务器详情模态框 */}
      <Modal
        title={`服务器详情 - ${selectedServer?.name}`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={900}
      >
        {detailLoading ? (
          <div style={{ textAlign: 'center', padding: '50px' }}>
            <Spin size="large" />
          </div>
        ) : selectedServer ? (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: 16 }}>
              <Descriptions.Item label="服务器名称">{selectedServer.name}</Descriptions.Item>
              <Descriptions.Item label="连接状态">
                <Space>
                  {getStatusIcon(selectedServer.status)}
                  <Badge
                    status={getStatusColor(selectedServer.status) as any}
                    text={getStatusText(selectedServer.status)}
                  />
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="服务器URL">{selectedServer.serverUrl}</Descriptions.Item>
              <Descriptions.Item label="超时时间">{selectedServer.connectTimeoutMs}ms</Descriptions.Item>
              <Descriptions.Item label="激活状态">
                <Badge status={selectedServer.isActive ? 'success' : 'default'} text={selectedServer.isActive ? '激活' : '禁用'} />
              </Descriptions.Item>
              <Descriptions.Item label="最后连接时间">
                {selectedServer.lastConnectedAt ? new Date(selectedServer.lastConnectedAt).toLocaleString() : '从未连接'}
              </Descriptions.Item>
              {selectedServer.description && (
                <Descriptions.Item label="描述" span={2}>
                  {selectedServer.description}
                </Descriptions.Item>
              )}
            </Descriptions>

            <Tabs
              defaultActiveKey="tools"
              items={[
                {
                  key: 'tools',
                  label: `可用工具 (${serverTools.length})`,
                  children: (
                    <List
                      dataSource={serverTools}
                      renderItem={tool => (
                        <List.Item>
                          <List.Item.Meta
                            avatar={<Avatar icon={<SettingOutlined />} />}
                            title={tool.name}
                            description={tool.description}
                          />
                        </List.Item>
                      )}
                      locale={{ emptyText: '暂无可用工具' }}
                    />
                  )
                },
                {
                  key: 'resources',
                  label: `可用资源 (${serverResources.length})`,
                  children: (
                    <List
                      dataSource={serverResources}
                      renderItem={resource => (
                        <List.Item>
                          <List.Item.Meta
                            avatar={<Avatar icon={<EyeOutlined />} />}
                            title={resource.name}
                            description={resource.uri}
                          />
                        </List.Item>
                      )}
                      locale={{ emptyText: '暂无可用资源' }}
                    />
                  )
                }
              ]}
            />
          </div>
        ) : null}
      </Modal>
    </div>
  );
};

export default McpServerList;